<template>
  <el-dialog
    class="subject-status-add-record"
    :title="dialogTitle"
    width="600px"
    :show-close="true"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form :rules="rules" ref="formRef" size="mini" :model="formData" label-width="140px">
      <!-- 是否生效 -->
      <el-form-item label="是否生效：">
        <el-radio-group v-model="formData.takeEffect">
          <el-radio label="1">生效</el-radio>
          <el-radio label="0">失效</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 实验室检查项变量 -->
      <el-form-item label="实验室检查项变量：">
        <el-select style="width: 80%" v-model="formData.checkItemVariables">
          <el-option
            v-for="item in checkItemVariablesOptions"
            :key="item.codeValue"
            :label="item.codeNameCn"
            :value="item.codeValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 实验室检查项值 -->
      <el-form-item label="实验室检查项值：">
        <el-cascader
          v-model="formData.checkItemValue"
          :options="checkItemValueOptions"
          :props="props"
          clearable
          style="width: 80%"
        ></el-cascader>
      </el-form-item>
      <!-- 实验室检查结果值 -->
      <el-form-item label="实验室检查结果值：">
        <div>
          <i class="el-icon-circle-plus" style="font-size: 30px" @click="btnAddCheckResultValueOptions()"></i>
        </div>
        <div v-for="(item, index) in checkResultValueOptions" :key="index" style="margin-bottom: 4px">
          <el-input v-model="item.value" style="width: 80%" placeholder="请输入"></el-input
          ><i
            @click="btnDelCheckResultValueOptions(item.id)"
            class="el-icon-delete"
            style="color: red; margin-left: 8px"
          ></i>
        </div>
      </el-form-item>
      <!-- 临床意义 -->
      <el-form-item label="临床意义：">
        <el-select style="width: 80%" v-model="formData.clinicalSignificance">
          <el-option
            v-for="item in clinicalSignificanceOptions"
            :key="item.codeValue"
            :label="item.codeNameCn"
            :value="item.codeValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 临床意义选择的值 -->
      <el-form-item label="临床意义选择的值：">
        <el-select style="width: 80%" v-model="formData.clinicalSignificanceSelectionValues" multiple>
          <el-option
            v-for="item in clinicalSignificanceSelectionValuesOptions"
            :key="item.codeValue"
            :label="item.codeNameCn"
            :value="item.codeValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 质疑方式 -->
      <el-form-item label="质疑方式：">
        <el-select size="mini" v-model="formData.way" placeholder="请选择" style="width: 80%">
          <el-option
            v-for="item in questioningModeList"
            :key="item.value"
            :value="item.value"
            :label="item.text"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="dialogTitle === '复制'">
        <p style="color: red"><i class="el-icon-info"></i>复制前请先修改数据！</p>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="handleSave">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapActions } from 'vuex'
import { generateRandomId } from '@/utils/modules/tableConLogic.js'
import { cloneDeep } from 'lodash-es'

export default {
  props: {
    editData: Object,
    dialogVisible: Boolean,
    dialogTitle: String,
    questioningModeList: Array,
    searchParams: Object,
    filters: Object,
  },
  data() {
    return {
      rules: {},
      loading: false,
      defaultFormData: {
        takeEffect: '',
        checkItemVariables: '',
        checkItemValue: '',
        clinicalSignificance: '',
        clinicalSignificanceSelectionValues: [],
        way: '',
      },
      formData: {},
      checkResultValueOptions: [],
      clinicalSignificanceOptions: [],
      clinicalSignificanceSelectionValuesOptions: [],
      checkItemVariablesOptions: [],
      checkItemValueOptions: [],
      props: { multiple: true },
    }
  },

  watch: {
    dialogVisible(val) {
      if (val) {
        const editDataDeep = cloneDeep(this.editData)
        // 将checkItemValue(实验室检查项值)由字符串转换成数组
        if (editDataDeep.checkItemValue) {
          const array = editDataDeep.checkItemValue.split(',')
          const emptyArray = []
          array.forEach(item => {
            const string = item
            emptyArray.push([item.split('|')[0], string])
          })
          editDataDeep.checkItemValue = emptyArray
        }
        // 实验室检查结果值由字符串转换成数组
        if (editDataDeep.checkResultValue) {
          const arr = editDataDeep.checkResultValue.split(',')
          arr.forEach(item => {
            this.checkResultValueOptions.push({
              value: item,
              id: generateRandomId(),
            })
          })
        }
        // 临床意义选择的值由字符串转换成数组
        if (editDataDeep.clinicalSignificanceSelectionValues) {
          editDataDeep.clinicalSignificanceSelectionValues = editDataDeep.clinicalSignificanceSelectionValues.split(',')
        }

        this.formData = { ...editDataDeep }

        // 获取下拉项
        Promise.all([
          this.getClinicalSignificance(),
          this.getClinicalSignificanceSelectionValues(),
          this.getCheckItemVariables(),
          this.getCheckItemValue(),
        ])
      } else {
        this.formData = { ...this.defaultFormData }
      }
    },
  },

  methods: {
    ...mapActions('verificationRule', [
      'copySelectListEcNormalValueQualitativeAPI',
      'updateSelectListEcNormalValueQualitativeAPI',
      'getClinicalSignificanceAPI',
      'getClinicalSignificanceSelectionValuesAPI',
      'getCheckItemVariablesAPI',
      'getCheckItemValueAPI',
    ]),

    // 点击删除
    btnDelCheckResultValueOptions(id) {
      this.checkResultValueOptions = this.checkResultValueOptions.filter(item => item.id !== id)
    },

    // 点击加号
    btnAddCheckResultValueOptions() {
      this.checkResultValueOptions.push({
        value: '',
        id: generateRandomId(),
      })
    },

    // 1. 获取临床意义下拉项
    async getClinicalSignificance() {
      const params = {
        ...this.searchParams,
        ...this.filters,
        variable: this.editData.variable,
      }
      params.surface = this.editData.surface
      const res = await this.getClinicalSignificanceAPI({ params })
      this.clinicalSignificanceOptions = [res.data]
    },
    // 2. 临床意义选择的值下拉项
    async getClinicalSignificanceSelectionValues() {
      const params = {
        ...this.searchParams,
        ...this.filters,
        variable: this.editData.variable,
      }
      params.surface = this.editData.surface
      const res = await this.getClinicalSignificanceSelectionValuesAPI({ params })
      this.clinicalSignificanceSelectionValuesOptions = res.data
    },
    // 3. 获得实验室检查项变量下拉项
    async getCheckItemVariables() {
      const params = {
        ...this.searchParams,
        ...this.filters,
        variable: this.editData.variable,
      }
      params.surface = this.editData.surface
      const res = await this.getCheckItemVariablesAPI({ params })
      this.checkItemVariablesOptions = [res.data]
    },

    // 4. 获得实验室检查项值下拉项
    async getCheckItemValue() {
      const params = {
        ...this.searchParams,
        ...this.filters,
        variable: this.editData.variable,
      }
      params.surface = this.editData.surface
      const res = await this.getCheckItemValueAPI({ params })
      this.checkItemValueOptions = this.updateProperties(res.data)
    },

    // 改变实验室检查项值的属性名
    updateProperties(obj) {
      if (Array.isArray(obj)) {
        return obj.map(item => this.updateProperties(item))
      } else if (typeof obj === 'object' && obj !== null) {
        const newObj = {}
        for (let key in obj) {
          if (key === 'codeNameCn') {
            newObj['label'] = obj[key]
          } else if (key === 'codeValue') {
            newObj['value'] = obj[key]
          } else {
            newObj[key] = this.updateProperties(obj[key])
          }
        }
        return newObj
      } else {
        return obj
      }
    },

    // 保存提交
    handleSave() {
      this.loading = true
      this.$refs.formRef.validate(valid => {
        if (valid) {
          // 临床意义选择的值由数组改为字符串
          this.formData.clinicalSignificanceSelectionValues =
            this.formData.clinicalSignificanceSelectionValues.join(',')
          // 设置检查结果值
          const arr = this.checkResultValueOptions.map(item => item.value)
          const string = arr.join(',')
          this.formData.checkResultValue = string
          // 编辑
          if (this.dialogTitle === '编辑') {
            const data = {
              reqDTOList: [this.formData],
            }
            // 设置checkItemValue从数组改成字符串
            let str = ''
            data.reqDTOList[0].checkItemValue.forEach(item => {
              if (str) {
                str = str + ',' + item[1]
              } else {
                str = str + item[1]
              }
            })
            data.reqDTOList[0].checkItemValue = str
            this.updateSelectListEcNormalValueQualitativeAPI({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '编辑成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.formData = { ...this.defaultFormData }
                this.checkResultValueOptions = []
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          }
          // 复制
          else {
            const data = {
              ...this.formData,
            }
            // 设置checkItemValue从数组改成字符串
            let str = ''
            data.checkItemValue.forEach(item => {
              if (str) {
                str = str + ',' + item[1]
              } else {
                str = str + item[1]
              }
            })
            data.checkItemValue = str
            this.copySelectListEcNormalValueQualitativeAPI({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '复制成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.formData = { ...this.defaultFormData }
                this.checkResultValueOptions = []
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          }
        } else {
          this.loading = false
          return false
        }
      })
    },

    // 关闭取消
    handleClose() {
      // 表单数据清除
      this.formData = { ...this.defaultFormData }
      this.checkResultValueOptions = []
      this.$emit('handleCancel')
    },
  },
}
</script>
<style lang="scss" scoped>
.span-dropdown-item {
  display: inline-block;
  width: 120%;
}
</style>
